<template>
  <MenuPage 
  :columns="columns" 
        :data="dataList" 
        :loading="tableLoading" 
        :total="listTotal"
        :page.sync="pageIndex"
        :size.sync="pageSize"
        @queryFun="getToolList">
    <template slot="search">
        <Button type="primary" ghost class="md-add-jh" @click="addFlowModal">新建工具</Button>
        <Divider type="vertical" />
        <div style="height: 32px;line-height: 32px;flex-shrink: 0;">
          <Checkbox v-model="creatByMeModal" @on-change="getDataList(1)">由我创建</Checkbox>
        </div>
        <Input
          clearable
          v-model.trim="toolName"
          placeholder="工具名称"
          @on-change="getDataList(1)"
          style="width: 180px;margin-left: 15px"
        />
        <Select filterable
          v-model="visibility"
          clearable
          @on-change="getDataList(1)"
          placeholder="可见范围"
          style="width: 150px;margin-left: 15px"
        >
          <Option value="share">单位</Option>
          <Option value="private">个人</Option>
        </Select>
        <Select filterable
          v-model="type"
          clearable
          @on-change="getDataList(1)"
          placeholder="工具类型"
          style="width: 150px;margin-left: 15px;"
        >
          <Option v-for="item in typeList" :key="item.dictid" :value="item.dictid">{{
            item.dictname
          }}</Option>
        </Select>
        <Select filterable
          v-model="suitableSystem"
          clearable
          @on-change="getDataList(1)"
          placeholder="适用系统"
          style="width: 150px;margin-left: 15px;"
        >
          <Option value="Windows">Windows</Option>
          <Option value="Linux">Linux</Option>
          <Option value="Unix">Unix</Option>
          <Option value="macOS">macOS</Option>
        </Select>
        <Button
          class="header-btn"
          type="primary"
          ghost
          style="height: 32px;margin-left: 5px;"
          @click="refreshData()"
        >
          <i class="el-icon-refresh-right" />
        </Button>
      </template>
  <Modal
        v-model="showModal"
        :mask-closable="false"
        width="500"
        @on-visible-change="changeVisible"
        :closable="false"
        :title="title1"
      >
        <Form ref="formItem" :model="formItem" :rules="formItemRule" :label-width="100">
          <FormItem label="工具名称" prop="name">
            <Input v-model.trim="formItem.name" placeholder="工具名称长度为1-64个字符"></Input>
          </FormItem>
          <FormItem label="可见范围" prop="visibility">
            <RadioGroup v-model="formItem.visibility">
              <Radio label="share">单位</Radio>
              <Radio label="private">个人</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="适用系统" prop="suitableSystem">
            <Select filterable v-model="formItem.suitableSystem">
              <Option value="Windows">Windows</Option>
            <Option value="Linux">Linux</Option>
            <Option value="Unix">Unix</Option>
            <Option value="macOS">macOS</Option>
            </Select>
          </FormItem>
          <FormItem label="工具类型" prop="type">
            <Select filterable v-model="formItem.type">
              <Option v-for="item in typeList" :key="item.dictid" :value="item.dictid">{{
                item.dictname
              }}</Option>
            </Select>
          </FormItem>
      
          <FormItem label="工具源文件" prop="fileName">
            <part-upload
              @upload-success="changeFile"
              @del-item="deleteFile"
              @upload-loading="handleFileUploading"
              :isSingle="true"
              :Unlimited="true"
              :fileList="toolFileList"
              :isConfirm="false"
              :allFileType="true"
            ></part-upload>
          </FormItem>
       
          <FormItem label="工具说明手册" prop="guideName">
            <part-upload
              @upload-success="changeGuide"
              @del-item="deleteGuide"
              @upload-loading="handleFileUploading"
              fileType="docs"
              :isSingle="true"
              :isConfirm="false"
              :fileList="guideList"
              :formatArr="['doc', 'docx', 'pdf']"
            ></part-upload>
          </FormItem>
          <FormItem label="预期结果" prop="expectation">
            <Input v-model.trim="formItem.expectation"></Input>
          </FormItem>
          <FormItem label="常用参数" prop="parameter">
            <Input v-model.trim="formItem.parameter"></Input>
          </FormItem>
          <FormItem label="工具进程" prop="process">
            <Input v-model.trim="formItem.process"></Input>
          </FormItem>
          <FormItem label="版本信息" prop="version">
            <Input v-model.trim="formItem.version"></Input>
          </FormItem>
          <FormItem label="描述" prop="description">
            <Input
              v-model.trim="formItem.description"
              type="textarea"
              :maxlength="200"
              :autosize="{ minRows: 2, maxRows: 5 }"
              placeholder="描述"
            ></Input>
          </FormItem>
        </Form>
        <template slot="footer">
          <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
          <Button
            type="primary"
            @click="formBtn('formItem')"
            :disabled="fileUploading"
            :loading="loading"
            >确定</Button
          >
        </template>
      </Modal>
</MenuPage>
</template>

<script>
import PartUpload from "@/components/item-upload/partUpload.vue";
import $ from 'jquery';
import encryption from '@/libs/encryption.js';
import { getToolList, getToolDetail, addTools, updateTool, deleteTools } from '@/api/tool';
import ItemUpload from '@/components/item-upload';
import { validateName1 } from '@/libs/reg';
import { allDirection } from '@/api/dict';
import pageTitle from '@/mixin/pageTitle';
import { debounce } from '@/libs/utils';
export default {
  mixins: [pageTitle],
  components: {
    ItemUpload,
    PartUpload,
  },
  data() {
    const validateUpload = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择文件'));
      } else {
        callback();
      }
    };
    return {
      creatByMeModal: false,
      typeList: [],
      suitableSystem: '',
      type: '',
      toolFileList: [],
      guideList: [],
      // 用户信息
      USER_ID: '',
      isRootDesigner: '',
      // 页面设置
      fullHeight: document.documentElement.clientHeight,
      fullWidth: document.documentElement.clientWidth,
      setTableHei: 'auto',
      // 数据
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      listTotal: 0,
      toolName: '',
      visibility: '',
      tableLoading:true,
      columns:[
      {
        title: '名称',
        key: 'name',
        tooltip:true
      },
      {
        type:'link',
        title: '源文件',
        key: 'fileName',
        setPath:(data) => {
          return `/api/minio/download?path=${data.path}`
        },
        tooltip:true
      },
      {
        type:'link',
        title: '使用手册',
        key: 'guideName',
        setPath:(data) => {
          return `/api/minio/download?path=${data.guidePath}`
        },
        tooltip:true
      },
      {
        title: '工具类型',
        key: 'typeName',
        tooltip:true
      },
      {
        title: '适用系统',
        key: 'suitableSystem',
        tooltip:true
      },
      {
        title: '可见范围',
        key: 'visibility',
        filter:(visibility) => {
          return visibility === 'share' ? '单位' : '个人'
        },
        setColor:(visibility) => {
          return visibility === 'share' ? 'rgb(50, 205, 50)' : 'rgb(255, 165, 0)'
        },
        tooltip:true
      },
      {
        title: '描述',
        key: 'description',
        tooltip:true
      },
      {
        title: '创建者',
        key: 'creatorName'
      },
      {
        title: '创建时间',
        key: 'created',
        tooltip:true
      },
      {
        title:'操作',
        key:'action',
        opList:[{
            txt:'修改',
            type:'modify',
            disabled:this.setIsClick,
            fun:this.updateTool1
          },
          {
            txt:'删除',
            title:'确认删除？',
            type:'delete',
            tooltip:true,
            disabled:this.setIsClick,
            fun:(data)=> {
              return this.deleteTools(data.id)
            }
          }
        ]
      }],
      // 查看Flow
      showModal: false,
      isAdd: false,
      upLoadUrl: ``,
      loading: false,
      fileUploading: false,
      title1: '创建工具',
      formItem: {
        name: '',
        description: '',
        expectation: '',
        file: null,
        guide: null,
        fileName: '',
        path: '',
        guideName: '',
        guidePath: '',
        parameter: '',
        process: '',
        suitableSystem: 'windows',
        type: '',
        version: '',
        visibility: 'share'
      },
      formItemRule: {
        name: [
          { required: true, message: '工具名称不能为空', trigger: 'change,blur' },
          { max: 64, message: '工具名称长度为1-64个字符', trigger: 'change,blur' },
          { validator: validateName1, trigger: 'change,blur' }
        ],
        visibility: [{ required: true, message: '可见范围不能为空', trigger: 'change,blur' }],
        suitableSystem: [{ required: true, message: '适用系统不能为空', trigger: 'change,blur' }],
        type: [{ required: true, message: '工具类型不能为空', trigger: 'change,blur' }],
        fileName: [{ required: true, validator: validateUpload, trigger: 'change,blur' }],
        guideName: [{ required: true, validator: validateUpload, trigger: 'change,blur' }]
      }
    };
  },
  created() {
    // 获取用户id
    let November = sessionStorage.getItem('November');
    November = JSON.parse(encryption.SelfUseDecrypt(November));
    this.USER_ID = November.userId;
    this.isRootDesigner = November.isRootDesigner;
    this.upLoadUrl = `api/minio/upload/permanent?visibility=company&type=pcap&bucket=pcap`;
  },
  async mounted() {
    // this.setStyle();
    // window.addEventListener('resize', this.setStyle);
    await this.getTypeList().then();
    this.getToolList();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setStyle);
  },
  methods: {
    getTypeList() {
      return new Promise((resolve) => {
        allDirection({
          dictTypeID: 'tools'
        })
          .then(({ code, message, attribute = {} }) => {
            if (code !== 1) {
              this.$Message.warning(message);
              return;
            }
            this.typeList =
              (attribute &&
                attribute.attribute &&
                attribute.attribute[0] &&
                attribute.attribute[0].dictEntryList) ||
              [];
          })
          .catch(() => {
            this.$Message.error('获取工具类型列表异常');
          })
          .finally(() => {
            resolve();
          });
      });
    },
    changeVisible(type) {
      if (!type) {
        this.$refs.formItem.resetFields();
        this.toolFileList = [];
        this.guideList = [];
      }
    },
    handleFileUploading(status) {
      this.fileUploading = status;
    },
    // 添加使用手册，设置数据
    changeGuide(file) {
      this.formItem.guide = file;
      this.formItem.guideName = file.fileName;
      this.formItem.guidePath = file.filePath;
      this.guideList = [
        {
          id: file.fileId,
          fileName: file.fileName,
          path: file.filePath
        }
      ];
      this.$nextTick(() => {
        this.$refs.formItem.validateField('guideName');
      });
    },
    deleteGuide() {
      this.formItem.guide = null;
      this.formItem.guideName = '';
      this.formItem.guidePath = '';
      this.guideList = [];
      this.$nextTick(() => {
        this.$refs.formItem.validateField('guideName');
      });
    },
    // 添加了源文件，设置数据
    changeFile(file) {
      this.formItem.file = file;
      this.formItem.fileName = file.fileName;
      this.formItem.path = file.filePath;
      this.toolFileList = [
        {
          id: file.fileId,
          fileName: file.fileName,
          path: file.filePath
        }
      ];
      this.$nextTick(() => {
        this.$refs.formItem.validateField('fileName');
      });
    },
    // 删除源文件，将相关数据清除
    deleteFile() {
      this.formItem.file = null;
      this.formItem.fileName = '';
      this.formItem.path = '';
      this.toolFileList = [];
      this.$nextTick(() => {
        this.$refs.formItem.validateField('fileName');
      });
    },
    // 设置高度
    setStyle() {
      window.fullHeight = document.documentElement.clientHeight;
      window.fullWidth = document.documentElement.clientWidth;
      this.fullHeight = window.fullHeight;
      this.fullWidth = window.fullWidth;
      this.setTableHei = this.fullHeight - 197;
      this.pageSize = Math.floor(this.setTableHei / 96) || 1;
    },
    // Flow列表
    getToolList: debounce(function() {
      this.tableLoading = true
      getToolList({
        pageIndex: this.pageIndex,
        pageSize: this.pageSize,
        name: this.toolName,
        suitableSystem: this.suitableSystem,
        type: this.type,
        visibility: this.visibility,
        createByMe: this.creatByMeModal ? this.USER_ID : undefined
      })
        .then((res) => {
          if (res.data.code == 1) {
            let pageList = res.data.data;
            this.listTotal = parseInt(pageList.total);
            this.dataList = (pageList.items || []).map((item) => {
              item.typeName = this.getTypeName(item.type);
              return item;
            });
          } else {
            this.dataList = [];
            this.listTotal = 0;
            this.$Message.warning(res.data.message);
          }
          this.tableLoading = false
        })
        .catch((err) => {
          this.tableLoading = false
        });
    }, 500),
    getTypeName(typeId) {
      let template = this.typeList.find((item) => item.dictid === typeId);
      return template ? template.dictname : '';
    },
    getDataList(val) {
      this.pageIndex = val;
      this.getToolList();
    },
    // 添加Flow
    addFlowModal() {
      this.showModal = true;
      this.loading = false;
      this.formItem.visibility = 'share';
      this.formItem.file = null;
      this.isAdd = true;
      this.title1 = '创建工具';
    },
    // 修改Flow
    updateTool1(row) {
      this.showModal = true;
      this.loading = false;
      this.title1 = '修改工具';
      this.isAdd = false;
      this.formItem = Object.assign({}, row);
      if (this.formItem.fileName) {
        this.toolFileList = [
          {
            fileName: this.formItem.fileName,
            path: this.formItem.path
          }
        ];
      }
      if (this.formItem.guideName) {
        this.guideList = [
          {
            fileName: this.formItem.guideName,
            path: this.formItem.guidePath
          }
        ];
      }
    },
    // 删除
    deleteTools(id) {
      deleteTools(id)
        .then((res) => {
          if (res.data.code == 1) {
            this.$Message.success('删除成功');
            this.pageIndex =
              this.pageIndex > 1 && this.dataList.length === 1
                ? this.pageIndex - 1
                : this.pageIndex;
            this.getToolList();
          } else {
            this.$Message.warning(res.data.message);
          }
        })
        .catch((err) => {
          this.$Message.error('删除异常');
        });
    },
    // 刷新Flow
    refreshData() {
      this.pageIndex = 1;
      this.suitableSystem = '';
      this.type = '';
      this.toolName = '';
      this.visibility = '';
      this.creatByMeModal = false
      this.getToolList();
    },
    // 计算index
    handleProIndex(key) {
      return (this.pageIndex - 1) * this.pageSize + key + 1;
    },
    // 设置知否可点击
    setIsClick(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return true //{ 'pointer-events': 'none' };
      }
    },
    setImgSrc(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../assets/project/modifys.png');
      } else {
        return require('../../assets/project/modifys-h.png');
      }
    },
    setDelImgSrc(item) {
      if (item.isshare === 'public' || (item.creator !== this.USER_ID && !this.isRootDesigner)) {
        return require('../../assets/project/delNote-d.png');
      } else {
        return require('../../assets/project/delNote-h.png');
      }
    },
    cancelUpload() {
      this.$refs['formItem'].resetFields();
      this.showModal = false;
    },
    formBtn(name) {
      if (this.isAdd) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.loading = true;
            addTools(this.formItem)
              .then((res) => {
                if (res.data.code === 1) {
                  this.showModal = false;
                  this.refreshData();
                  this.$Message.success('创建工具成功');
                } else {
                  this.$Message.warning(res.data.message);
                }
              })
              .catch(() => {
                this.$Message.error('创建工具异常');
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            this.$Message.error('请完善信息！');
          }
        });
      } else {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.loading = true;
            updateTool(this.formItem)
              .then((res) => {
                if (res.data.code === 1) {
                  this.showModal = false;
                  this.$Message.success('修改工具成功');
                  this.getToolList();
                } else {
                  this.$Message.warning(res.data.message);
                }
              })
              .catch(() => {
                this.$Message.error('修改工具异常');
              })
              .finally(() => {
                this.loading = false;
              });
          } else {
            this.$Message.error('请完善信息！');
          }
        });
      }
    }
  }
};
</script>
<style scoped>
</style>
